package com.kong.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.kong.constant.MessageConstant;
import com.kong.dao.OrderSettingDao;
import com.kong.pojo.OrderSetting;
import com.kong.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yang2013
 * @data 2020/10/12 18:04
 */
@Service
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Override
    public void batchInsert(List<Map> excelList) {
        if (excelList.size()>0 && excelList!=null){
            orderSettingDao.batchInsert(excelList);
        }
    }

    @Override
    public void updateOrderSetting(OrderSetting orderSetting) {
        OrderSetting orderSetting1=orderSettingDao.findByDate(orderSetting.getOrderDate());
        if (orderSetting1==null){
            orderSettingDao.add(orderSetting);
        }else {
            //修改的可预约人数不能小于已经预约的人数
            if (orderSetting1.getReservations()>orderSetting.getNumber()){
                throw new RuntimeException(MessageConstant.ORDERSETTING_FAIL);
            }
            orderSettingDao.updataOrderSetting(orderSetting);
        }
    }

    @Override
    public List<Map> findAll(String orderDate) {
        String startDate=orderDate+"-01";
        String endDate=orderDate+"-31";
        Map map=new HashMap();
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        List<OrderSetting> orderSettings=orderSettingDao.findAll(map);
        List<Map> mapList = orderSetting2Map(orderSettings);
        return mapList;
    }

    @Override
    public void deleteOrderSetting(String date) {
        if (StringUtils.isEmpty(date)){
            throw new RuntimeException("传入日期为空");
        }
        //备份数据
        List<OrderSetting> orderSettings=orderSettingDao.findMemberCountBeforeDate(date);
        if (orderSettings!=null && orderSettings.size()>0){
            orderSettingDao.batchInsertOrderSetting(orderSettings);
            orderSettingDao.deleteByDate(date);
        }
    }


    /**
     *装配返回给前端的数据
     * @param orderSettings
     */
    private List<Map> orderSetting2Map(List<OrderSetting> orderSettings) {
        List<Map> mapList=new ArrayList<>();
        for (OrderSetting orderSetting : orderSettings) {
            Map map1=new HashMap();

            map1.put("date",orderSetting.getOrderDate().getDate());
            map1.put("number",orderSetting.getNumber());
            map1.put("reservations",orderSetting.getReservations());
            mapList.add(map1);
        }
        return mapList;
    }
}
